useId is a React Hook for generating unique, stable identifiers that are consistent between server and client rendering, solving problems related to accessibility and hydration mismatches.
It provides a straightforward way to generate a unique and stable ID for each instance of a component. Its primary purpose is to solve the problem of creating accessible components—like connecting an <input> with its <label> via the id and htmlFor attributes—without the risk of duplicate IDs or hydration errors that come with manually generating IDs using methods like Math.random() .
Stable Across Renders: Once generated, the ID for a component instance remains the same for its entire lifetime. This ensures that a <label> stays correctly associated with its <input>, and that accessibility relationships are not broken on re-renders .
SSR and Hydration-Safe: This is the hook's biggest advantage over ad-hoc ID generation. It is specifically designed to work with Server-Side Rendering (SSR). React ensures that the ID generated on the server matches the ID generated on the client during hydration, eliminating warnings and runtime errors .
Ideal for Accessibility (a11y): useId is the recommended tool for generating IDs needed for ARIA attributes like aria-describedby, aria-labelledby, or simply for linking labels and inputs. It helps create a more robust and reliable experience for users of assistive technologies .
No Arguments: The hook is called with no arguments, making it simple and declarative .
Internal Counter: Behind the scenes, useId manages an internal counter that is aware of the component tree's structure. The generated IDs (e.g., :r1:, :r2:) are not meant to be human-readable, but are guaranteed to be unique for the component's position in the tree .
Keys in Lists: The React documentation explicitly advises against using useId to generate keys for list items. Keys should be derived from your data, as they need to be stable across different renders and component instances .
DOM References: If you simply need a reference to a DOM element for programmatic manipulation (like focusing an input), the useRef hook is the correct tool, not useId .
Styling: Using IDs for CSS styling is generally not recommended in component-based architectures, where CSS Modules or CSS-in-JS are preferred.
In summary, useId is a dedicated tool for a specific job. It elegantly solves the long-standing challenge of creating hydration-safe and unique identifiers for accessibility purposes, making reusable component libraries and complex server-rendered applications more robust and easier to build .